package portal.bean;

import java.io.IOException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import java.util.List;

import javax.faces.model.SelectItem;

import oracle.stellent.ridc.IdcClient;
import oracle.stellent.ridc.IdcClientException;
import oracle.stellent.ridc.IdcContext;
import oracle.stellent.ridc.model.DataBinder;
import oracle.stellent.ridc.model.DataObject;
import oracle.stellent.ridc.model.DataResultSet;
import oracle.stellent.ridc.protocol.ServiceResponse;

import oracle.webcenter.content.integration.Node;
import oracle.webcenter.content.integration.el.support.ValueWrapperImpl;
import oracle.webcenter.framework.service.JSFUtils;


import org.apache.myfaces.trinidad.component.UIXIterator;
import org.apache.myfaces.trinidad.model.SortableModel;

import portal.Global;
import portal.UtilsContent;

public class VbckBean {
    private String tieude = "";
    private Date Ngaybanhhanh;
    private Date Ngayhieuluc;
    private String Cqbh;
    private String loaivb;
    private String linhvuc;
    private String ngonngu;
    private String noidungVB;
    private String noidung;
    private String trichyeu;
    private Date tungay;
    private Date denngay;
    private String sohieuvanban;
    private String linhvucValue;
    private String loaivanbanValue;
    private String coquanbanhanhValue;
    private List<SelectItem> lstLinhvucItems = new ArrayList<SelectItem>();
    private List<SelectItem> lstLoaivanbanItems = new ArrayList<SelectItem>();
    private List<SelectItem> lstCoquanbanhanhItems =
        new ArrayList<SelectItem>();
    private List<DataObject> lstVBCK = new ArrayList<DataObject>();
    private List<DataObject> lstReferenceVBCK = new ArrayList<DataObject>();
    private List<DataObject> lstAttachFileVBCK = new ArrayList<DataObject>();
    private List<DataObject> lstLinhvuc;
    private List<DataObject> lstLoaivanban;
    private List<DataObject> lstCoquanbanhanh;
    private List<DataObject> lstNgonngu;
    private int currentPage = 1;
    private int selectedPage = 1;
    private int numberOfResult = 1;
    private int numberOfPage = -1;

    private List<String> pagesnumber = new ArrayList<String>();
    private boolean hasnextpage;
    private String functionrequest = "";
    private Date ngaybanhanh;
    private UIXIterator iteratorNodes;
    private boolean hasAttachFile = false;

    public VbckBean() {
        super();
        if (!isPostback()) {
            lstLinhvuc = UtilsContent.getdslinhvuc();
            lstLoaivanban = UtilsContent.getdsloaibanban();
            lstCoquanbanhanh = UtilsContent.getdscoquanbanhanh();
            lstNgonngu = UtilsContent.getdsNgonngu();
        }
    }

    protected boolean isPostback() {
        return Boolean.TRUE.equals(JSFUtils.resolveExpression("#{adfFacesContext.postback}"));
    }


    /**
     * @creator
     * @comment
     * @param tungay
     * @param denngay
     * @param sohieuvanban
     * @param trichyeu
     * @param linhvuc
     * @param loaivanban
     * @param coquanbanhanh
     * @return
     */
    private String createQueryString(Date tungay, Date denngay,
                                     String sohieuvanban, String trichyeu,
                                     String linhvuc, String loaivanban,
                                     String coquanbanhanh,
                                     String languagecode) {
        String queryString = "dDocType <contains> `VBCK`";
        if (tungay != null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
            queryString +=
                    " <AND> xmNgaybanhanh >= `" + df.format(tungay) + "`";
        }
        if (denngay != null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
            queryString +=
                    " <AND> xmNgaybanhanh < `" + df.format(denngay) + "`";
        }
        if (sohieuvanban != null && !sohieuvanban.equals("")) {
            sohieuvanban = sohieuvanban.toLowerCase().replaceAll("<qsch>", "");
            sohieuvanban =
                    sohieuvanban.toLowerCase().replaceAll("</qsch>", "");
            queryString +=
                    " <AND> <qsch>dDocTitle:" + sohieuvanban + "</qsch>";
        }
        if (trichyeu != null && !trichyeu.equals("")) {
            trichyeu = trichyeu.toLowerCase().replaceAll("<qsch>", "");
            trichyeu = trichyeu.toLowerCase().replaceAll("</qsch>", "");
            queryString += " <AND> <qsch>xComments:" + trichyeu + "</qsch>";
        }
        if (linhvuc != null && !linhvuc.equals(""))
            queryString += " <AND> xmLinhvuc <matches> `" + linhvuc + "`";
        if (loaivanban != null && !loaivanban.equals(""))
            queryString += " <AND> xmLoaivb <matches> `" + loaivanban + "`";
        if (coquanbanhanh != null && !coquanbanhanh.equals(""))
            queryString += " <AND> xmCqbh <matches> `" + coquanbanhanh + "`";
        if (noidung != null && !noidung.equals("")) {
            noidung = noidung.toLowerCase().replaceAll("<ftx>", "");
            noidung = noidung.toLowerCase().replaceAll("</ftx>", "");
            queryString += " <AND> (<ftx>" + noidung + "</ftx>)";
        }
        if (languagecode != null && !languagecode.equals("")) {
            queryString += " <AND> xmNgonngu <matches> `" + languagecode + "`";
        }
        return queryString;
    }

    /**
     * @creator
     * @comment
     * @param selectedPage
     */
    private void getListWithPaging(int selectedPage) {
        int startRow = 1;

        try {
            numberOfResult = iteratorNodes.getRowCount();
            if (numberOfResult > 0) {
                startRow = numberOfResult * (selectedPage - 1) + 1;
                String querystring =
                    createQueryString(tungay, denngay, sohieuvanban, trichyeu,
                                      linhvucValue, loaivanbanValue,
                                      coquanbanhanhValue,
                                      LocaleBean.getCurrentInstance().getUserLocale().getLanguage());
                System.out.print(querystring);
                DataResultSet drs =
                    UtilsContent.SearchUCMContent(querystring, "xmNgaybanhanh",
                                                  numberOfResult, startRow, 0,
                                                  "DESC",
                                                  Global.getIdcClient(),
                                                  Global.getUserContext());
                lstVBCK = drs.getRows();
                if (drs.getRows().size() == numberOfResult) {
                    startRow = numberOfResult * (selectedPage) + 1;
                    drs =
UtilsContent.SearchUCMContent(querystring, "xmNgaybanhanh", numberOfResult,
                              startRow, 0, "DESC", Global.getIdcClient(),
                              Global.getUserContext());
                    if (drs.getRows().size() > 0)
                        hasnextpage = true;
                    else
                        hasnextpage = false;
                } else
                    hasnextpage = false;
                //Thiet lap chuoi link toi cac trang dang: "...2 3 4 5 6... "
                if (pagesnumber.size() > 0)
                    pagesnumber.clear();
                if (selectedPage > 1) {
                    pagesnumber.add(String.valueOf(selectedPage - 1));
                    pagesnumber.add(String.valueOf(selectedPage));

                } else if (selectedPage == 1)
                    pagesnumber.add("1");
                if (hasnextpage) {
                    pagesnumber.add(String.valueOf(selectedPage + 1));
                }
                UtilsContent.setPageFlowScope("pagesnumber", pagesnumber);
                UtilsContent.setPageFlowScope("currentPage", selectedPage);
                UtilsContent.setPageFlowScope("hasnextpage", hasnextpage);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * @creator
     * @comment
     * @param loaivanban
     * @param ngaybanhanh
     */
    private void listReferenceVBPL(String loaivanban, Date ngaybanhanh,String dDocName) {
        String querystring =
            createQueryString(null, ngaybanhanh, "", "", "", loaivanban, "",
                              LocaleBean.getCurrentInstance().getUserLocale().getLanguage());
        //System.out.print(querystring);
        querystring += " <AND> <NOT> dDocName <matches> `" + dDocName  + "`";  
        DataResultSet drs =
            UtilsContent.SearchUCMContent(querystring, "xmNgaybanhanh", 10, 0,
                                          0, "DESC", Global.getIdcClient(),
                                          Global.getUserContext());
        lstReferenceVBCK = drs.getRows();
    }


    private void listAttachfile(String dID, String dDocName) {
        DataResultSet drs =
            UtilsContent.getAttachfilesInfo(dID, dDocName, Global.getIdcClient(),
                                            Global.getUserContext());
        lstAttachFileVBCK = drs.getRows();

        System.out.print(drs.getRows().size());
    }

    public String timKiemButtonClick() {
        try {
            getListWithPaging(1);
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return null;
    }

    public void setNgaybanhhanh(Date Ngaybanhhanh) {
        this.Ngaybanhhanh = Ngaybanhhanh;
    }

    public Date getNgaybanhhanh() {

        try {
            ValueWrapperImpl obj =
                (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmNgaybanhanh'].value}");
            Calendar cld = obj.getCalendarValue();
            Ngaybanhhanh = cld.getTime();
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }


        return Ngaybanhhanh;
    }

    public void setNgayhieuluc(Date Ngayhieuluc) {
        this.Ngayhieuluc = Ngayhieuluc;
    }

    public Date getNgayhieuluc() {

        try {
            ValueWrapperImpl obj =
                (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmNgayhieuluc'].value}");
            if (obj != null) {
                Calendar cld = obj.getCalendarValue();
                Ngayhieuluc = cld.getTime();
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return Ngayhieuluc;
    }

    public void setCqbh(String Cqbh) {
        this.Cqbh = Cqbh;
    }

    public String getCqbh() {
        try {
            Object obj =
                JSFUtils.resolveExpression("#{node.propertyMap['xmCqbh'].value}");
            String id = obj.toString();
            for (DataObject item : lstCoquanbanhanh) {
                if (id.equals(item.get("ID"))) {
                    Cqbh = item.get("TEN");
                    break;
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return Cqbh;
    }

    public void setLoaivb(String loaivb) {
        this.loaivb = loaivb;
    }

    public String getLoaivb() {
        try {
            Object obj =
                JSFUtils.resolveExpression("#{node.propertyMap['xmLoaivb'].value}");
            String id = obj.toString();            
            obj = JSFUtils.resolveExpression("#{node.propertyMap['dID'].value}");
            String dID = obj.toString();
            obj = JSFUtils.resolveExpression("#{node.propertyMap['dDocName'].value}");
            String dDocName = obj.toString(); 
            //listReferenceVBPL(id, null,dDocName);
            for (DataObject item : lstLoaivanban) {
                if (id.equals(item.get("ID"))) {
                    loaivb = item.get("TEN");
                    break;
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }

        return loaivb;
    }

    public void setLinhvuc(String linhvuc) {
        this.linhvuc = linhvuc;
    }

    public String getLinhvuc() {
        try {
            Object obj =
                JSFUtils.resolveExpression("#{node.propertyMap['xmLinhvuc'].value}");
            String id = obj.toString();
            for (DataObject item : lstLinhvuc) {
                if (id.equals(item.get("ID"))) {
                    linhvuc = item.get("TEN");
                    break;
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return linhvuc;
    }

    public void setNgonngu(String ngonngu) {
        this.ngonngu = ngonngu;
    }

    public String getNgonngu() {
        try {
            Object obj =
                JSFUtils.resolveExpression("#{node.propertyMap['xmNgonngu'].value}");
            String id = obj.toString();
            for (DataObject item : lstNgonngu) {
                if (id.equals(item.get("ID"))) {
                    ngonngu = item.get("TEN");
                    break;
                }
            }
        } catch (Exception e) {
            // TODO: Add catch code
            e.printStackTrace();
        }
        return ngonngu;
    }

    public void setNoidungVB(String noidungVB) {
        this.noidungVB = noidungVB;
    }

    public String getNoidungVB() {
        if (!functionrequest.contains("getNoidungVB")) {
            ValueWrapperImpl vwrp =
                (ValueWrapperImpl)oracle.webcenter.framework.view.JSFUtils.resolveExpression("#{node.propertyMap['dDocName'].value}");
            String dDocName = vwrp.getStringValue();
            vwrp = (ValueWrapperImpl)oracle.webcenter.framework.view.JSFUtils.resolveExpression("#{node.propertyMap['dID'].value}");
            String dID = vwrp.getStringValue();
            try {
                noidungVB = UtilsContent.getDocContent(dID,dDocName);   
                lstAttachFileVBCK =  UtilsContent.listAttachfile(dID, dDocName);
                Object obj =
                    JSFUtils.resolveExpression("#{node.propertyMap['xmLoaivb'].value}");
                String id = obj.toString();               
                ValueWrapperImpl obj1 = (ValueWrapperImpl)JSFUtils.resolveExpression("#{node.propertyMap['xmNgaybanhanh'].value}");
                Calendar cld = obj1.getCalendarValue();
                Ngaybanhhanh = cld.getTime();
                listReferenceVBPL(id, Ngaybanhhanh,dDocName);
            } catch (IdcClientException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return noidungVB;
    }

    public void setNoidung(String noidung) {
        this.noidung = noidung;
    }

    public String getNoidung() {
        return noidung;
    }

    public void setLinhvucValue(String linhvucValue) {
        this.linhvucValue = linhvucValue;
    }

    public String getLinhvucValue() {
        return linhvucValue;
    }

    public void setLoaivanbanValue(String loaivanbanValue) {
        this.loaivanbanValue = loaivanbanValue;
    }

    public String getLoaivanbanValue() {
        return loaivanbanValue;
    }

    public void setCoquanbanhanhValue(String coquanbanhanhValue) {
        this.coquanbanhanhValue = coquanbanhanhValue;
    }

    public String getCoquanbanhanhValue() {
        return coquanbanhanhValue;
    }

    public void setTrichyeu(String trichyeu) {
        this.trichyeu = trichyeu;
    }

    public String getTrichyeu() {
        return trichyeu;
    }

    public void setTungay(Date tungay) {
        this.tungay = tungay;
    }

    public Date getTungay() {
        return tungay;
    }

    public void setDenngay(Date denngay) {
        this.denngay = denngay;
    }

    public Date getDenngay() {
        return denngay;
    }

    public void setSohieuvanban(String sohieuvanban) {
        this.sohieuvanban = sohieuvanban;
    }

    public String getSohieuvanban() {
        return sohieuvanban;
    }

    public void setLstLinhvucItems(List<SelectItem> lstLinhvucItems) {

        this.lstLinhvucItems = lstLinhvucItems;
    }

    public List<SelectItem> getLstLinhvucItems() {
        lstLinhvuc = UtilsContent.getdslinhvuc();
        for (DataObject obj : lstLinhvuc) {
            SelectItem item = new SelectItem();
            item.setLabel(obj.get("TEN"));
            item.setValue(obj.get("ID"));
            lstLinhvucItems.add(item);

        }
        return lstLinhvucItems;
    }

    public void setLstLoaivanbanItems(List<SelectItem> lstLoaivanbanItems) {
        this.lstLoaivanbanItems = lstLoaivanbanItems;
    }

    public List<SelectItem> getLstLoaivanbanItems() {
        lstLoaivanban = UtilsContent.getdsloaibanban();
        for (DataObject obj : lstLoaivanban) {
            SelectItem item = new SelectItem();
            item.setLabel(obj.get("TEN"));
            item.setValue(obj.get("ID"));
            lstLoaivanbanItems.add(item);
        }
        return lstLoaivanbanItems;
    }

    public void setLstCoquanbanhanhItems(List<SelectItem> lstCoquanbanhanhItems) {
        this.lstCoquanbanhanhItems = lstCoquanbanhanhItems;
    }

    public List<SelectItem> getLstCoquanbanhanhItems() {
        lstCoquanbanhanh = UtilsContent.getdscoquanbanhanh();
        for (DataObject obj : lstCoquanbanhanh) {
            SelectItem item = new SelectItem();
            item.setLabel(obj.get("TEN"));
            item.setValue(obj.get("ID"));
            lstCoquanbanhanhItems.add(item);
        }
        return lstCoquanbanhanhItems;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getCurrentPage() {
        if (UtilsContent.getPageFlowScope("currentPage") != null)
            currentPage =
                    (Integer)UtilsContent.getPageFlowScope("currentPage");
        return currentPage;
    }

    public void setSelectedPage(int selectedPage) {
        this.selectedPage = selectedPage;
    }

    public int getSelectedPage() {
        return selectedPage;
    }

    public void setNumberOfResult(int numberOfResult) {
        this.numberOfResult = numberOfResult;
    }

    public int getNumberOfResult() {
        return numberOfResult;
    }

    public void setPagesnumber(List<String> pagesnumber) {
        this.pagesnumber = pagesnumber;
    }

    public List<String> getPagesnumber() {
        if (UtilsContent.getPageFlowScope("pagesnumber") != null)
            pagesnumber =
                    (List<String>)UtilsContent.getPageFlowScope("pagesnumber");
        return pagesnumber;
    }

    public void setHasnextpage(boolean hasnextpage) {
        this.hasnextpage = hasnextpage;
    }

    public boolean isHasnextpage() {
        if (UtilsContent.getPageFlowScope("hasnextpage") != null)
            hasnextpage =
                    (Boolean)UtilsContent.getPageFlowScope("hasnextpage");
        return hasnextpage;
    }

    public void setLstVBCK(List<DataObject> lstVBCK) {
        this.lstVBCK = lstVBCK;
    }

    public List<DataObject> getLstVBCK() {
        return lstVBCK;
    }

    public void setTieude(String tieude) {
        this.tieude = tieude;
    }

    public String getTieude() {
        return tieude;
    }

    public void setNgaybanhanh(Date ngaybanhanh) {
        this.ngaybanhanh = ngaybanhanh;
    }

    public Date getNgaybanhanh() {
        Object obj = JSFUtils.resolveExpression("#{node.xmNgaybanhanh}");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        try {
            ngaybanhanh = format.parse(obj.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return ngaybanhanh;
    }

    public String pageSeleted() {
        getListWithPaging(selectedPage);
        return null;
    }

    public String nextPage() {
        if (UtilsContent.getPageFlowScope("currentPage") != null)
            currentPage =
                    (Integer)UtilsContent.getPageFlowScope("currentPage");
        selectedPage = currentPage + 1;
        getListWithPaging(currentPage + 1);
        return null;
    }

    public String prevPage() {
        if (UtilsContent.getPageFlowScope("currentPage") != null)
            currentPage =
                    (Integer)UtilsContent.getPageFlowScope("currentPage");
        if (currentPage > 1) {
            selectedPage = currentPage - 1;
            getListWithPaging(currentPage - 1);
        }
        return null;
    }

    public void setNumberOfPage(int numberOfPage) {
        this.numberOfPage = numberOfPage;
    }

    public int getNumberOfPage() {
        return numberOfPage;
    }

    public void setIteratorNodes(UIXIterator iteratorNodes) {
        this.iteratorNodes = iteratorNodes;
        if (!isPostback()) {
            getListWithPaging(1);
        }
    }

    public UIXIterator getIteratorNodes() {
        return iteratorNodes;
    }

    public void setLstReferenceVBCK(List<DataObject> lstReferenceVBCK) {
        this.lstReferenceVBCK = lstReferenceVBCK;
    }

    public List<DataObject> getLstReferenceVBCK() {
        return lstReferenceVBCK;
    }

    public void setLstAttachFileVBCK(List<DataObject> lstAttachFileVBCK) {
        this.lstAttachFileVBCK = lstAttachFileVBCK;
    }

    public List<DataObject> getLstAttachFileVBCK() {
        return lstAttachFileVBCK;
    }

    public void setHasAttachFile(boolean hasAttachFile) {
        this.hasAttachFile = hasAttachFile;
    }

    public boolean isHasAttachFile() {
        if(lstAttachFileVBCK.size()>0)
            hasAttachFile = true;
        return hasAttachFile;
    }
}
